package com.example.chatapp.redis;

import com.example.chatapp.websocket.WebSocketSessionManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import java.util.Map;

public class RedisMessageSubscriber implements MessageListener {
    private final WebSocketSessionManager sessionManager;
    private final ObjectMapper mapper = new ObjectMapper();

    public RedisMessageSubscriber(WebSocketSessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String msg = new String(message.getBody());
        String channelName = new String(message.getChannel());
        
        System.out.println("========================================");
        System.out.println("[RedisMessageSubscriber] Received message on channel: " + channelName);
        System.out.println("[RedisMessageSubscriber] Subscriber instance: " + this.hashCode());
        
        try {
            // 解析消息以获取 roomId，只广播到对应房间
            Map<String, Object> msgMap = mapper.readValue(msg, Map.class);
            String roomId = (String) msgMap.get("roomId");
            Long seq = msgMap.get("seq") != null ? ((Number) msgMap.get("seq")).longValue() : null;
            
            if (roomId != null) {
                System.out.println("[RedisMessageSubscriber] Broadcasting to room: " + roomId + ", seq: " + seq);
                sessionManager.broadcastToRoom(roomId, msg);
            } else {
                // 如果没有 roomId，广播到所有会话（向后兼容）
                System.out.println("[RedisMessageSubscriber] Broadcasting to all sessions (no roomId)");
                sessionManager.broadcast(msg);
            }
        System.out.println("========================================");
        } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
            System.err.println("[RedisMessageSubscriber] JSON parsing error: " + e.getMessage());
            // JSON 解析失败，尝试作为普通文本广播
            try {
                sessionManager.broadcast(msg);
            } catch (Exception ex) {
                System.err.println("[RedisMessageSubscriber] Failed to broadcast after JSON error: " + ex.getMessage());
            }
        } catch (Exception e) {
            System.err.println("[RedisMessageSubscriber] Unexpected error: " + e.getClass().getName() + " - " + e.getMessage());
            // 不重新抛出异常，避免影响其他消息的处理
        }
    }
}
